package com.woniu.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.car.common.ResponseEntity;

import com.woniu.car.Util.NumberCreate;
import com.woniu.car.client.PlatformClient;
import com.woniu.car.domain.TGoodDetail;
import com.woniu.car.domain.TGoods;
import com.woniu.car.domain.TOrderGoods;
import com.woniu.car.domain.TProductCategory;
import com.woniu.car.dto.OrderDto;
import com.woniu.car.exception.ParamException;
import com.woniu.car.mapper.TGoodDetailMapper;
import com.woniu.car.mapper.TGoodsMapper;
import com.woniu.car.mapper.TOrderGoodsMapper;
import com.woniu.car.mapper.TProductCategoryMapper;
import com.woniu.car.ortherModel.CouponSearchParameter;
import com.woniu.car.ortherModel.TCoupon;
import com.woniu.car.param.GoodsListParam;
import com.woniu.car.param.GoodsOrderParam;
import com.woniu.car.service.TOrderGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chestnuts
 * @since 2021-06-21
 */
@Slf4j
@Service
public class TOrderGoodsServiceImpl extends ServiceImpl<TOrderGoodsMapper, TOrderGoods> implements TOrderGoodsService {


    @Resource
    private RedissonClient redissonClient;

    @Resource
    private TGoodsMapper goodsMapper;
    @Resource
    private TOrderGoodsMapper orderGoodsMapper;

    @Resource
    private TProductCategoryMapper productCategoryMapper;

    @Resource
    private TGoodDetailMapper goodDetailMapper;

    @Resource
    private PlatformClient platformClient;

    @Override
    public ResponseEntity placeGoodsOrder(@Valid GoodsOrderParam goodsOrderParam, int id) throws InterruptedException {




        //获得优惠券对象 得到信息
//        couponSearchParameter.getDeductionMoney();
//        couponSearchParameter.getDiscountMoney();
//        couponSearchParameter.getFullMoney();


        //先不管优惠券
        List<GoodsListParam> goodsListParams = goodsOrderParam.getGoodsListParams();
        //构造订单对象
        String no=NumberCreate.getOrderNO();
        TOrderGoods tOrderGoods = new TOrderGoods();
        tOrderGoods.setOrderNumber(no);
        tOrderGoods.setUserId(id);
        tOrderGoods.setCreateTime(new Date());
        tOrderGoods.setPayStatus("1");
        tOrderGoods.setStatus("0");
        tOrderGoods.setAddr(goodsOrderParam.getAddr());



        List<TGoodDetail> tGoodDetailList = new ArrayList<>();
        Integer goodsId;
        Integer number;
        double total = 0.00;



        ResponseEntity responseEntity = null;

        //构造订单详情集合
        for(GoodsListParam i: goodsListParams){

            Double detailTotal = null;

            CouponSearchParameter couponSearchParameter = new CouponSearchParameter();

            couponSearchParameter.setCouponId(i.getCouponId());
            ResponseEntity responseEntity1 = platformClient.searchCoupon(i.getCouponId());
            log.info("asdas,{}",responseEntity1.getObject());
            ObjectMapper objectMapper = new ObjectMapper();
            TCoupon coupon = objectMapper.convertValue(responseEntity1.getObject(), TCoupon.class);



            log.info("asdas,{}",coupon);

            //准备单个的订单详情

            TGoodDetail tGoodDetail = new TGoodDetail();
            goodsId = i.getGoodsId();
            number = i.getNumber();
            TGoods tGoods = goodsMapper.selectById(goodsId);

            tGoodDetail.setDetailNumber(NumberCreate.getOrderDetailNO());
            tGoodDetail.setGoodId(goodsId);
            tGoodDetail.setOrderId(tOrderGoods.getOrderId());
            tGoodDetail.setGoodName(tGoods.getGoodsName());
            TProductCategory category = productCategoryMapper.selectById(tGoods.getCategoryId());

            tGoodDetail.setKind(category.getCategoryName());
            tGoodDetail.setGoodsImg(tGoods.getImage());
            tGoodDetail.setNumber(number);
            tGoodDetail.setPrice(tGoods.getGoodsPrice());

            tGoodDetail.setTotal(number * tGoods.getGoodsPrice());



            if(!coupon.getStatus().equals("0"))return new ResponseEntity().setObject(coupon).setMsg("优惠券不能生效").setCode(509);

            if(1==coupon.getType()){
                Double fullMoney = coupon.getFullMoney();
                detailTotal = (number * tGoods.getGoodsPrice()) - fullMoney;
                tGoodDetail.setDiscountMoney(fullMoney);
            }else if(2==coupon.getType()){
                Double discountMoney = coupon.getDiscountMoney()-0.1;
                detailTotal = (number * tGoods.getGoodsPrice()) * discountMoney;
                tGoodDetail.setDiscountMoney((number * tGoods.getGoodsPrice())*(1-discountMoney));
            }else if(3==coupon.getType()){
                Double deductionMoney = coupon.getDeductionMoney();
                detailTotal = (number * tGoods.getGoodsPrice()) - deductionMoney;
                tGoodDetail.setDiscountMoney(deductionMoney);
            }else{
                new ResponseEntity().setObject(coupon).setMsg("优惠券种类不符").setCode(509);
            }

            tGoodDetail.setRealPrice(detailTotal);

            tGoodDetailList.add(tGoodDetail);

            //优惠券待处理
            log.info("asdads,{}",detailTotal);
            total=total+detailTotal;
        }



        tOrderGoods.setTotal(total);

        RLock lock = redissonClient.getLock("goodsOrder:lock:" + no);

        boolean res = lock.tryLock(10, 5, TimeUnit.SECONDS);
        if (res) {
            try {
                orderGoodsMapper.insert(tOrderGoods);
            } finally {
                lock.unlock();
            }
        }


        TOrderGoods order = orderGoodsMapper.selectOne(new QueryWrapper<TOrderGoods>().eq("order_number", no));

        List<TGoodDetail> tGoodDetails = new ArrayList<>();
        for(TGoodDetail i:tGoodDetailList){
            i.setOrderId(order.getOrderId());
            goodDetailMapper.insert(i);
            TGoodDetail goodDetail = goodDetailMapper.selectOne(new QueryWrapper<TGoodDetail>().eq("detail_number", i.getDetailNumber()));
            tGoodDetails.add(goodDetail);
        }


        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(order,orderDto);
        orderDto.setGoodDetailList(tGoodDetails);


        return new ResponseEntity().setCode(200).setMsg("下单成功").setObject(orderDto);
    }

    @Override
    public ResponseEntity putGoodsOrderStatus(Integer orderId) throws ParamException {
        TOrderGoods tOrderGoods = orderGoodsMapper.selectById(orderId);
        if(tOrderGoods==null){
            throw new ParamException("该订单不存在");
        }
        UpdateWrapper<TOrderGoods> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 2).set("pay_time",new Date()).eq("order_id",orderId);
        int update = orderGoodsMapper.update(tOrderGoods, wrapper);
        TOrderGoods order = orderGoodsMapper.selectById(orderId);
        return new ResponseEntity().setCode(200).setMsg("支付成功修改订单状态,添加支付时间成功").setObject(order);
    }

    @Override
    public ResponseEntity OverOrderStatus(Integer orderId) throws ParamException {
        TOrderGoods tOrderGoods = orderGoodsMapper.selectById(orderId);
        if(tOrderGoods==null){
            throw new ParamException("该订单不存在");
        }
        UpdateWrapper<TOrderGoods> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 3).set("pay_status",2).set("over_time",new Date()).eq("order_id",orderId);
        int update = orderGoodsMapper.update(tOrderGoods, wrapper);
        TOrderGoods order = orderGoodsMapper.selectById(orderId);
        return new ResponseEntity().setCode(200).setMsg("完成订单,添加完成时间,修改状态").setObject(order);
    }



}
